from flask import Flask, redirect, request, jsonify

# 实例化Flask类
app = Flask(__name__)

# 装饰器
@app.route("/")
def hello_world():
    return "hello world"

@app.route("/hey/<username>")
def hey(username: str):
    return "heyhey %s" % username

# @app.route("/my/<int:num>")
@app.route("/my/<float:num>")
def my_num(num):
    return "my %s" % (num + num)

# 重定向
@app.route("/baidu")
def go_baidu():
    return redirect("https://www.baidu.com")

@app.route("/test/my/first", methods=["POST", "GET"])
def first_post():
    try:
        my_json = request.get_json()
        print(my_json)
        # return "good"

        get_name = my_json.get("name")
        # return get_name
        # 可以进行改造
        get_age = my_json.get("age")

        if not all ( [get_name, get_age] ):
            return jsonify( msg="出错了，缺少参数" )
        
        # 进行数据处理
        # get_age += 10

        # return get_age
        return jsonify(name=get_name, age=get_age)

    except Exception as e:
        print("[error] is: " + e)
        return jsonify( msg="出错了，未知错误" )


'''
127.0.0.1 这一台电脑 本地的内网ip
等同于localhost
5000是端口号
相当于楼号和房间号
'''

# app.run()
app.run( host="0.0.0.0" ) #任何主机都能访问

# 增删改查
# POST DELETE PUT GET

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0')



